package com.bootcamp.servlet.uploadfile;

/**
 * @program: wrok-1101
 * @description: ${description}
 * @author: Keyu Li
 * @create: 2021-11-02 19:45
 **/

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.*;

@WebServlet(name = "UploadImgServlet", value = "/uploadimg")
public class UploadImgServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (!isMultipart) {
            response.getWriter().println("<h1>please make sure upload a file!");
            return;
        }

        // create a new file uploader and set max size
        ServletFileUpload fileUpload = new ServletFileUpload();
        fileUpload.setFileSizeMax(1024*1024);
        // parse request and get iterator
        try {
            FileItemIterator itemIterator = fileUpload.getItemIterator(request);
            while (itemIterator.hasNext()) {
                FileItemStream item = itemIterator.next();
                String name = item.getFieldName();
                InputStream inputStream = item.openStream();
                if (item.isFormField()) {
                    System.out.println("Form field " + name + " with value "
                            + Streams.asString(inputStream,"utf-8") + " detected.");
                } else {
                    System.out.println("File field " + name + " with file name "
                            + item.getName() + " detected.");
                    // write to file
                    String filePath = request.getServletContext().getRealPath("resources/" + item.getName());
                    parseStreamToImg(inputStream, new File(filePath));
                    // response to browser
                    String relativePath = request.getContextPath() + "/resources/" + item.getName();
                    transferToResponse(inputStream, relativePath, response);
                }
                inputStream.close();
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        }

    }

    private void transferToResponse(InputStream inputStream, String filePath, HttpServletResponse response) {
        response.setStatus(200);
        System.out.println(filePath);
        response.setHeader("refresh", "2;url=" + filePath);
        try {
            response.getWriter().println("<h1>upload img succeed! please wait 2 seconds!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void parseStreamToImg(InputStream inputStream, File file) {
        if (!file.getParentFile().exists() || file.getParentFile().isFile()) {
            file.getParentFile().mkdirs();
        }
        // input read and output write
        FileOutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(file);
            byte[] bytes = new byte[2048];
            int length;
            while ((length = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, length);
            }
            outputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
